package com.cch.android.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.FloatMath;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cch.android.imageutil.ImageUtil;
import com.cch.android.util.Constant;
import com.cch.android.util.MyLog;

public class KusoImageActivity extends Activity implements OnClickListener{
	
	private Context context;
	
	private View mImageView;
	
	/**
	 * 初始化的图片
	 */
	private static Bitmap bmpInit;
	
	 private static Bitmap bitmap; 
	
	private LinearLayout opeanimagelay,cameraimagelay;
	private FrameLayout kusoLay;
	
	private AlertDialog myDialog;
	
	private Button homeBtn,saveBtn;
	
	private  String SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory()
    + File.separator + "tmpPhoto.jpg";
	
	private MyView view;
	
	private static int m_screenWidth;

	private static int m_screenHeight;
	
	  @Override
	   public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.model_setimage_kuso);
		 m_screenWidth = Constant.m_screenWidth;
	     m_screenHeight = Constant.m_screenHeight;
		context = this;
		Constant.createSDCardDir(context);//创建文件夹
		initView();
		changePic();//选择图片
	  }
	  private void initView(){
//		  mImageView = (View)findViewById(R.id.kuso_image_view);
		  homeBtn = (Button)findViewById(R.id.setimage3_home_btn);
		  saveBtn = (Button)findViewById(R.id.setimage3_save_btn);
		  kusoLay = (FrameLayout)findViewById(R.id.kuso_image_lay);
		  homeBtn.setOnClickListener(this);
		  saveBtn.setOnClickListener(this);
//		  mImageView.setOnTouchListener(this);
	  }
	  private void changePic() {
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.layout.dialog_open, null);
			opeanimagelay = (LinearLayout)layout.findViewById(R.id.openimage);
			cameraimagelay = (LinearLayout)layout.findViewById(R.id.cameraimage);
			opeanimagelay.setOnClickListener(this);
			cameraimagelay.setOnClickListener(this);
			myDialog = new AlertDialog.Builder(context).create();
			myDialog.show();
			myDialog.getWindow().setContentView(layout);
		}
//	@Override
//	public boolean onTouch(View v, MotionEvent event) {
//		switch (event.getAction()) {
//		case MotionEvent.ACTION_DOWN:
//			int rawX = (int) event.getRawX();
//			int rawY = (int) event.getRawY();
////			view.mess(rawX, rawX);
//			break;
//		case MotionEvent.ACTION_MOVE:
//			break;
//
//		default:
//			break;
//		}
//		return false;
//	}

	@Override
	public void onClick(View v) {
             switch (v.getId()) {
			case R.id.setimage3_home_btn:
				if(myDialog!=null)
				 myDialog.dismiss();
				finish();
				break;
			case R.id.setimage3_save_btn:
//				Drawable drawable = imageView.getDrawable();
//				if(drawable!=null)
//					try {
//						String filePath = Constant.saveMyBitmap("cch_"+Constant.fileName, 100, drawable);
//						Toast toast = Toast.makeText(getApplicationContext(),
//							     "图片保存在:"+filePath, Toast.LENGTH_LONG);
//							   toast.setGravity(Gravity.CENTER, 0, 0);
//							   toast.show();
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
				
				
				break;
			case R.id.openimage:
				myDialog.dismiss();
				Intent getImage = new Intent(
						Intent.ACTION_GET_CONTENT);
				getImage.addCategory(Intent.CATEGORY_OPENABLE);
				getImage.setType("image/*");
				startActivityForResult(getImage, 0);
				break;
	       case R.id.cameraimage:
	    	   myDialog.dismiss();
		       
		       Intent takePictureFromCameraIntent = new Intent(
		    		    MediaStore.ACTION_IMAGE_CAPTURE);
		    		  takePictureFromCameraIntent.putExtra(
		    		    android.provider.MediaStore.EXTRA_OUTPUT, Uri
		    		      .fromFile(new File(SD_CARD_TEMP_DIR)));
		    		  startActivityForResult(takePictureFromCameraIntent, 1);
				break;
			}		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == 0) {
				Uri uri = data.getData();
				// Log.e("uri", uri.toString());
				ContentResolver cr = this.getContentResolver();
				try {
					 byte[] bmpByte = ImageUtil.streamToBytes(cr
								.openInputStream(uri));
					    long lenKb = ImageUtil.byteToKb(bmpByte.length);
					    System.out.println("读取图片大小："+lenKb);
					    BitmapFactory.Options opts =ImageUtil.setInSampleSize(lenKb);
						bmpInit = BitmapFactory.decodeStream(cr
								.openInputStream(uri),null,opts);
					/* 将Bitmap设定到ImageView */
//					mImageView.setImageBitmap(bmpInit);
					view = new MyView(this);
					view.setOnTouchListener(new OnTouchListener() {
						
						@Override
						public boolean onTouch(View v, MotionEvent event) {
							switch (event.getAction()) {
							case MotionEvent.ACTION_DOWN:
								int rawX = (int) event.getRawX();
								int rawY = (int) event.getRawY();
								view.mess(rawX, rawY);
								break;
							}
							return false;
						}
					});
					kusoLay.addView(view);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			} else if (requestCode == 1) {
				
				ContentResolver resolver = getContentResolver();
				  try {
					 byte[] mContent;
				   File f = new File(SD_CARD_TEMP_DIR);
				   try {
				    Uri capturedImage = Uri
				      .parse(android.provider.MediaStore.Images.Media
				        .insertImage(getContentResolver(), f
				          .getAbsolutePath(), null, null));
				    Toast toast = Toast.makeText(getApplicationContext(),
				      capturedImage.toString(), Toast.LENGTH_SHORT);
				    toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
				    toast.show();
				    //
				    // 将图片内容解析成字节数组
				    mContent = ImageUtil.readStream(resolver.openInputStream(Uri
				      .parse(capturedImage.toString())));
				    // 将字节数组转换为ImageView可调用的Bitmap对象
				    bmpInit = ImageUtil.getPicFromBytes(mContent, null);
				    // //把得到的图片绑定在控件上显示
				    bmpInit = ImageUtil.resizeBitmap(bmpInit, Constant.m_screenWidth, Constant.m_screenWidth+100);
				    MyLog.log("拍照返回:"+bmpInit);
				   } catch (FileNotFoundException e) {
				    // TODO Auto-generated catch block
				    e.printStackTrace();
				   }
				  } catch (Exception e) {
					  MyLog.log("拍照返回:"+e);
				   System.out.println(e.getMessage());
				  }
				
			}
			super.onActivityResult(requestCode, resultCode, data);
		}
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	 //  用于显示扭曲的图像  
    private static class MyView extends View  
    {  
        private static final int WIDTH = 20;  
        private static final int HEIGHT = 20;  
        private static final int COUNT = (WIDTH + 1) * (HEIGHT + 1);  
        private final float[] verts = new float[COUNT * 2];  
        private final float[] orig = new float[COUNT * 2];  
        private final Matrix matrix = new Matrix();  
        private final Matrix m = new Matrix();  
        
        //  设置verts数组的值  
        private static void setXY(float[] array, int index, float x, float y)  
        {  
            array[index * 2 + 0] = x;  
            array[index * 2 + 1] = y;  
        }  
        public MyView(Context context)  
        {  
            super(context);  
           
            setFocusable(true);  
            int w = bmpInit.getWidth();  
            int h = bmpInit.getHeight();   
//            ImageUtil.scalBitmap(bitmapOrg, newWidth, newHeight, 0);
            int index = 0;  
            //  生成verts和orig数组的初始值，这两个数组的值是一样的，只是在扭曲的过程中需要修改verts  
            //  的值，而修改verts的值要将原始的值保留在orig数组中  
            for (int y = 0; y <= HEIGHT; y++)  
            {  
                float fy = h * y / HEIGHT;  
                for (int x = 0; x <= WIDTH; x++)  
                {  
                    float fx = w * x / WIDTH;  
                    setXY(verts, index, fx, fy);  
                    setXY(orig, index, fx, fy);  
                    index += 1;  
                }  
            }  
            matrix.setTranslate((m_screenWidth-w)/2, (m_screenHeight-h)/2);  
//            matrix.setTranslate(10, 10); 
//            setBackgroundColor(Color.WHITE);  
        }  
        @Override  
        protected void onDraw(Canvas canvas)  
        {  
            canvas.concat(matrix);  
            canvas.drawBitmapMesh(bmpInit, WIDTH,HEIGHT, verts, 0, null, 0,null);  
        }  
        //  用于扭曲图像的方法，在该方法中根据当前扭曲的点（扭曲区域的中心点），也就是cx和cy参数，  
        //  来不断变化verts数组中的坐标值  
        private void warp(float cx, float cy)  
        {  
            final float K = 100000;   //  该值越大，扭曲得越严重（扭曲的范围越大）  
            float[] src = orig;  
            float[] dst = verts;  
            //  按一定的数学规则生成verts数组中的元素值  
            for (int i = 0; i < COUNT * 2; i += 2)  
            {  
                float x = src[i + 0];  
                float y = src[i + 1];  
                float dx = cx - x;  
                float dy = cy - y;  
                float dd = dx * dx + dy * dy;  
                float d = FloatMath.sqrt(dd);  
                float pull = K / ((float) (dd *d));  
                if (pull >= 1)  
                {  
                    dst[i + 0] = cx;  
                    dst[i + 1] = cy;  
                }  
                else  
                {  
                    dst[i + 0] = x + dx * pull;  
                    dst[i + 1] = y + dy * pull;  
                }  
            }  
        }  
        //  用于MyView外部控制图像扭曲的方法。该方法在handleMessage方法中被调用  
        public void mess(int x, int y)  
        {  
            float[] pt ={ x, y };  
            m.mapPoints(pt);  
            //  重新生成verts数组的值  
            warp(pt[0], pt[1]);  
            invalidate();  
        }  
    }  
}
